﻿using Inovout.Kuajing.Models;
using Inovout.Kuajing.Services;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Web.Http;

namespace Inovout.Kuajing.Web.Controllers
{
    public class DeclarationController : ApiController
    {
        private ShipmentOrderService shipmentOrderService = ComponentRegistry.Resolve<ShipmentOrderService>();
        [Route("v1/declaration/{tradeCode}")]
        [HttpPost]
        public JObject Notify(string tradeCode)
        {
            var contentWaiter = this.Request.Content.ReadAsStringAsync();
            contentWaiter.Wait();
            JObject body = JObject.Parse(contentWaiter.Result);
            bool success = (bool)body["success"];
            if (success)
            {
                shipmentOrderService.Ship(tradeCode);
            }
            else
            {
                var shipmentOrder = shipmentOrderService.GetByNo(tradeCode);
                shipmentOrder.Status = ShipmentOrderStatus.Closed;
                shipmentOrderService.Update(shipmentOrder);
            }
            JObject result = new JObject();
            result["trade_code"] = tradeCode;
            result["success"] = true;

            return result;
        }

        private Dictionary<string, string> csvOrderColumns = new Dictionary<string, string>{
             {"No","原始订单编号"},
            {"InOutFlag","进出口标志"},
             {"LogisticsCompanyCode","物流企业代码"},
            {"LogisticsCompanyName","物流企业名称"},
             {"LogisticsOrderNo","物流企业运单号"},
             {"Amount","订单商品货款"},
             {"Freight","订单商品运费"},
             {"Tax","订单税款总额"},
             {"ReceiverName","收货人名称"},
             {"ReceiverAddress","收货人地址"},
             {"ReceiverCountry","收货人所在国家"},
             {"PaymentCompanyCode","支付企业"},
             {"PaymentOrderNo","支付单号"},
              {"PaymentIdNo","支付人身份证号 "}
        };
        private Dictionary<string, string> csvOrderItemColumns = new Dictionary<string, string>{
             {"CommodityCode","企业商品货号"},
            {"CommodityBarCode","商品条形码"},
             {"CommodityQuantity","商品数量"},
            {"CommodityMeasurementUnit","计量单位"},
             {"CurrencyCode","币制代码"},
             {"Amount","商品总价"}
        };
        [Route("v1/declaration/pending")]
        [HttpGet]
        public HttpResponseMessage List()
        {
            StringBuilder sb = new StringBuilder();
            List<string> csvColumns = new List<string>(csvOrderColumns.Values);
            csvColumns.AddRange(csvOrderItemColumns.Values);
            WriteCsv(sb, csvColumns);
            List<ShipmentOrder> orders = shipmentOrderService.FindByStatus(ShipmentOrderStatus.Determining);
            foreach (var order in orders)
            {
                foreach (var item in order.Items)
                {
                    //临时处理NHibernate代理类出现的异常
                    item.Commodity = null;
                    order.Shipper = null;

                    JObject orderJObject = JObject.Parse(JsonConvert.SerializeObject(order, Formatting.Indented, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }));
                    orderJObject["InOutFlag"] = "I";
                    orderJObject["Freight"] = "0";
                    orderJObject["Tax"] = "0";
                    orderJObject["ReceiverCountry"] = "142";

                    JObject itemJObject = JObject.Parse(JsonConvert.SerializeObject(item, Formatting.Indented, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }));
                    itemJObject["CommodityBarCode"] = string.Empty;
                    itemJObject["CurrencyCode"] = "142";

                    List<string> cells = new List<string>();
                    foreach (var key in csvOrderColumns.Keys)
                    {
                        string cell = orderJObject[key].ToString();
                        cells.Add(cell);
                    }
                    foreach (var key in csvOrderItemColumns.Keys)
                    {
                        string cell = itemJObject[key].ToString();
                        cells.Add(cell);
                    }
                    WriteCsv(sb, cells);
                }

            }
            MemoryStream ms = new MemoryStream();
            byte[] bom = new byte[] { 0xEF, 0xBB, 0xBF };
            ms.Write(bom, 0, bom.Length);
            byte[] buffer = UTF8Encoding.UTF8.GetBytes(sb.ToString());
            ms.Write(buffer, 0, buffer.Length);
            ms.Position = 0;
            HttpContent content = new StreamContent(ms);
            content.Headers.ContentType = new MediaTypeHeaderValue("text/csv");
            content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".csv" };
            var response = this.Request.CreateResponse(HttpStatusCode.OK);
            response.Content = content;
            return response;
        }
        private void WriteCsv(StringBuilder sb, List<String> cells)
        {
            for (int i = 0; i < cells.Count; i++)
            {

                if (i > 0)
                {
                    sb.Append(",");
                }

                sb.Append(cells[i]);

            }
            sb.AppendLine();
        }
    }
}
